//
//  BVFavoriteViewController.m
//  AFNetworking
//
//  Created by 崔晋 on 2019/10/12.
//

#import "BVFavoriteViewController.h"
#import "BVService.h"
#import "BVMetaModel.h"
#import "BVFavoriteTableViewCell.h"
#import "BVVideoPlayView.h"
#import "Masonry.h"
#import "BVPopoverDateView.h"
#import "BVPopoverLocationVIew.h"

@interface BVFavoriteViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray<BVMetaModel *> *allDataSource;
@property (nonatomic, strong) NSMutableArray<BVMetaModel *> *dataSource;


@property (nonatomic, strong) BVPopoverDateView *dateView;
@property (nonatomic, strong) BVPopoverLocationVIew *locationView;
@end

@interface BVFavoriteViewController ()

@end

@implementation BVFavoriteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadInitData];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.dateView removeFromSuperview];
    self.dateView = nil;
    [self.locationView removeFromSuperview];
    self.locationView = nil;
}

- (void)setupViews {
    [self.tableView registerNib:[UINib nibWithNibName:@"BVFavoriteTableViewCell" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]] forCellReuseIdentifier:@"BVFavoriteTableViewCell"];
}

- (BOOL)navigationBarHidden {
    return NO;
}

- (void)setupNavigationBar {
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc] init];
    if (@available(iOS 8.2, *)) {
        titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightLight];
    } else {
        // Fallback on earlier versions
    }
    titleLabel.text = @"我的收藏";
    titleLabel.textColor = [UIColor colorFromHexString:@"#333333"];
    self.navigationItem.titleView = titleLabel;
    
    UIBarButtonItem *location = [[UIBarButtonItem alloc] initWithImage:[[UIImage bv_imageNamed:@"personal_location_icon" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(locationAct:)];
    
    self.navigationItem.rightBarButtonItems = @[location];
}

- (void)loadInitData {
    [[BVService shareInstance] get:@"vmeta" param:@{@"likes": @(YES)} complete:^(BOOL success, id  _Nullable response) {
        if (success) {
            [self handleDataWithData:response[@"data"][@"results"]];
            if (self.dataSource.count == 0) {
                [self errorView];
            }
        }else {
            [self errorView];
        }
    }];
}

- (void)errorView {
    __weak typeof(self)weakSelf = self;
    [BVErrorView showWithType:BVErrorViewTypeFavorite inView:self.view retryBlock:^{
        [weakSelf loadInitData];
    }];
}

- (void)handleDataWithData:(NSArray<NSDictionary *> *)dataArray {
    self.dataSource = [BVMetaModel arrayOfModelsFromDictionaries:dataArray error:nil];
    self.allDataSource = [BVMetaModel arrayOfModelsFromDictionaries:dataArray error:nil];
    [self.tableView reloadData];
}

- (void)playVideoWithIndexPath:(NSIndexPath *)indexPath model:(BVMetaModel *)model{
    BVFavoriteTableViewCell *cell = (BVFavoriteTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    BVVideoPlayView *view = [BVVideoPlayView sharedInstance];
    [cell.imageV addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(cell.imageV);
    }];
    view.url = [model.video buildUrlString];
    NSLog(@"play with url : %@", view.url);
    [view.playController prepareToPlay];
    [view.playController play];
}

- (void)locationAct:(UIBarButtonItem *)item {
    if (self.dateView && self.dateView.superview) {
        [self.dateView removeFromSuperview];
        self.dateView = nil;
    }
    if (self.locationView && self.locationView.superview) {
        [self.locationView removeFromSuperview];
        self.locationView = nil;
        return;
    }
    
    self.locationView = [BVPopoverLocationVIew showInView:self.view point:CGPointMake(kSCREEN_WIDTH - 23, kNavigationBarHeight + 2)];
    self.locationView.dataSource = [self handleLocationDataSource];
    
    
    __weak typeof(self)weakSelf = self;
    [self.locationView setDismissBlock:^{
        weakSelf.locationView = nil;
    }];
    self.locationView.selectLocation = ^(NSIndexPath * _Nonnull indexPath, BVMetaArena * _Nonnull model) {
        [weakSelf.tableView reloadData];
        if (model.objectId.length == 0) {
            weakSelf.dataSource = weakSelf.allDataSource.mutableCopy;
        }else {
            weakSelf.dataSource = [weakSelf.allDataSource filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(BVMetaModel *_Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
                if ([evaluatedObject.workout.arena.objectId isEqualToString:model.objectId]) {
                    return YES;
                }
                return NO;
            }]].mutableCopy;            
        }
            
        [weakSelf.tableView reloadData];
        [weakSelf.locationView removeFromSuperview];
        weakSelf.locationView = nil;
    };
}

- (void)dateAct:(UIBarButtonItem *)item {
    if (self.locationView && self.locationView.superview) {
        [self.locationView removeFromSuperview];
        self.locationView = nil;
    }
    if (self.dateView && self.dateView.superview) {
        [self.dateView removeFromSuperview];
        self.dateView = nil;
        
        return;
    }
    
    
    self.dateView = [BVPopoverDateView showInView:self.view point:CGPointMake(kSCREEN_WIDTH - 25, kNavigationBarHeight + 2)];
    
    __weak typeof(self)weakSelf = self;
    [self.dateView setDismissBlock:^{
        weakSelf.dateView = nil;
    }];
    
    [self.dateView setSelectDay:^(NSInteger year, NSInteger month, NSInteger day) {
        NSString *dateStr = [NSString stringWithFormat:@"%ld-%02ld-%02ld", (long)year, (long)month, (long)day];
        weakSelf.dataSource = [weakSelf.allDataSource filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(BVMetaModel *_Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
            if ([evaluatedObject.yyyyMMDDStr isEqualToString:dateStr]) {
                return YES;
            }
            return NO;
        }]].mutableCopy;
        [weakSelf.tableView reloadData];
        [weakSelf.dateView removeFromSuperview];
        weakSelf.dateView = nil;
    }];
}

- (NSArray<BVMetaArena *> *)handleLocationDataSource {
    NSMutableArray<BVMetaArena *> *tempArray = [NSMutableArray array];
    
    [self.allDataSource enumerateObjectsUsingBlock:^(BVMetaModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![tempArray containsObject:obj.workout.arena]) {
            [tempArray addObject:obj.workout.arena];
        }
    }];
    return tempArray.copy;
}

#pragma mark - tableview delegate and datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self playVideoWithIndexPath:indexPath model:self.dataSource[indexPath.row]];
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell isKindOfClass:[BVFavoriteTableViewCell class]]) {
        BVFavoriteTableViewCell *videoCell = (BVFavoriteTableViewCell *)cell;
        [videoCell.imageV.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj == [BVVideoPlayView sharedInstance]) {
                [[BVVideoPlayView sharedInstance] removeFromSuperview];
                [BVVideoPlayView sharedInstance].url = nil;
            }
        }];
        
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BVFavoriteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BVFavoriteTableViewCell" forIndexPath:indexPath];
    [cell configWithModel:self.dataSource[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [BVFavoriteTableViewCell cellHeight];
}

@end
